package com.example.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.Nullable;


import com.example.aidl.Book;
import com.example.aidl.IBookManager;
import com.example.aidl.IOnBookListener;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;


public class BookManagerService extends Service {

    private static final String TAG = "BookManagerService";
    private AtomicBoolean mIsServiceDestroyed = new AtomicBoolean(false);
    //CopyOnWriteArrayList支持并发读写，就是多个线程访问
    private CopyOnWriteArrayList<Book> mBookList = new CopyOnWriteArrayList<>();
    //保证关闭时取消新书消息推送
    private RemoteCallbackList<IOnBookListener> mListenerList = new RemoteCallbackList<>();

    private Binder mBinder = new IBookManager.Stub() {
        @Override
        public List<Book> getBookList() throws RemoteException {
            Log.e(TAG, "client getBookList: " + mBookList.size());
            return mBookList;
        }

        @Override
        public void addBook(Book book) throws RemoteException {
            mBookList.add(book);
            Log.e(TAG, "client addBook: " + book.bookName);
        }

        @Override
        public void registerListener(IOnBookListener listener) throws RemoteException {
            mListenerList.register(listener);
        }

        @Override
        public void unregisterListener(IOnBookListener listener) throws RemoteException {
            mListenerList.unregister(listener);
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        //服务端添加一些新书
        mBookList.add(new Book(1, "Android"));
        mBookList.add(new Book(2, "Ios"));
        new Thread(new ServiceWorker()).start();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mIsServiceDestroyed.set(true);
    }

    private void onNewBookArrived(Book book) throws RemoteException {
        //新书到来了
        mBookList.add(book);
        final int N = mListenerList.beginBroadcast();
        for (int i = 0; i < N; i++) {
            IOnBookListener listener = mListenerList.getBroadcastItem(i);
            if (listener != null) {
                listener.NewBookArrived(book);//将新书消息推给客户端
            }
            Log.d(TAG, "onNewBookArrived,notify listener:" + listener);
        }
        mListenerList.finishBroadcast();
    }

    private class ServiceWorker implements Runnable {
        @Override
        public void run() {
            //do background processing here
            while (!mIsServiceDestroyed.get()) {
                try {
                    Thread.sleep(5000);//5秒推送一次，5秒创建一本新书
                    int bookId = mBookList.size() + 1;
                    Book newBook = new Book(bookId, "new Book #" + bookId);
                    onNewBookArrived(newBook);//
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
